package com.android.delivery.activity.fragment

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.android.delivery.R
import com.android.delivery.activity.PrintlnActivity
import com.android.delivery.adapter.UnSendAdapter
import com.android.delivery.api.ApiService
import com.android.delivery.base.BaseListFragmet
import com.android.delivery.callback.DialogCallback
import com.android.delivery.callback.LzyResponse
import com.android.delivery.constant.Constants
import com.android.delivery.dialog.NavigationDialog
import com.android.delivery.dialog.PayMethodDialog
import com.android.delivery.entity.Logistics
import com.android.delivery.entity.PayWxInfo
import com.android.delivery.entity.even.RefreshConfirmPeison
import com.android.delivery.entity.even.RefreshPrint
import com.android.delivery.entity.even.WxPayEvent
import com.android.delivery.util.ToastUtils
import com.android.delivery.util.pay.WXPayCommon
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lzy.okgo.model.Response
import com.tencent.mm.opensdk.modelbase.BaseResp
import kotlinx.android.synthetic.main.include_refresh_layout.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 揽件列表
 */
class PeiSendListFragment : BaseListFragmet<Logistics>() {

    private var mClickPos = -1

    private val jieDanAdapter : UnSendAdapter by lazy {
        UnSendAdapter()
    }


    companion object {
        fun newInstance(type: Int): PeiSendListFragment {
            val fragment = PeiSendListFragment()
            val bundle = Bundle()
            bundle.putInt(Constants.TYPE, type)
            fragment.arguments = bundle
            return fragment
        }
    }

    private var type: Int = 0

    override fun bindRecyclerView(recLv: RecyclerView?) {
        type = arguments!!.getInt(Constants.TYPE)

        recLv!!.adapter = jieDanAdapter
        jieDanAdapter.setType(type)
        jieDanAdapter.setOnItemChildClickListener(object :BaseQuickAdapter.OnItemChildClickListener{
            override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                if (view?.id == R.id.tv_4){
                    mClickPos = position
                    val item = jieDanAdapter.getItem(position)
                    val payMethodDialog = PayMethodDialog.newInstance(item?.logisticsNo)
                    payMethodDialog.setOnGuardDialogListener(object :PayMethodDialog.OnPayMethodDialogListener{
                        override fun onBalancePay(orderNo: String) {
                            balancePay(orderNo, position)
                        }

                        override fun selectPic() {

                        }

                        override fun onWxPay(orderNo: String) {
                            wxPay(orderNo)
                        }

                    })
                    payMethodDialog.show(childFragmentManager)
                }else if (view?.id == R.id.tv_1){
                    val item = jieDanAdapter.getItem(position)
                    ApiService.deliveryTake(this, item!!.logisticsNo, 1, object : DialogCallback<LzyResponse<Any>>(){
                        override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                            ToastUtils.showShort(activity, "签收成功")
                            jieDanAdapter.data.removeAt(position)
                            jieDanAdapter.notifyItemRemoved(position)
                            EventBus.getDefault().post(RefreshConfirmPeison())
                        }
                    })
                }else if (view?.id == R.id.tv_2){
                    val item = jieDanAdapter.getItem(position)
                    ApiService.deliveryTake(this, item!!.logisticsNo, 2, object : DialogCallback<LzyResponse<Any>>(){
                        override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                            ToastUtils.showShort(activity, "签收成功")
                            jieDanAdapter.data.removeAt(position)
                            jieDanAdapter.notifyItemRemoved(position)
                            EventBus.getDefault().post(RefreshConfirmPeison())
                        }
                    })
                }else if (view?.id == R.id.tv_5){
                    val item = jieDanAdapter.getItem(position)
                    ApiService.printCloud(this, item!!.logisticsNo, object : DialogCallback<LzyResponse<Any>>() {
                        override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                            if (response?.body()?.code == 60001){
                                var intent = Intent(activity, PrintlnActivity::class.java)
                                intent.putExtra(Constants.ITEM, item)
                                intent.putExtra(Constants.TYPE, PrintlnActivity.TAB_PRINT_CLOUD)
                                startActivityForResult(intent, PrintlnActivity.REQUEST_CODE)
                            }else{
                                ToastUtils.showShort(activity, "打印成功")
                                onRefresh(refreshLayout)
                                EventBus.getDefault().post(RefreshPrint())
                            }
                        }
                    })
                }else if (view?.id == R.id.tv_navigation){
                    val item = jieDanAdapter.getItem(position)
                    val navigationDialog = NavigationDialog.newInstance(item?.getReceAddr())
                    navigationDialog.show(childFragmentManager)
                }
            }
        })
    }

    private val mUiHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1 && msg.obj != null) {
                val str = msg.obj as String
            }
        }
    }

    private fun balancePay(orderNo: String, position: Int) {
        ApiService.orderPayBalance(this, orderNo, object : DialogCallback<LzyResponse<Any>>(){
            override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                ToastUtils.showShort(activity, "支付成功")
                jieDanAdapter.getItem(position)?.paid = true
                jieDanAdapter.notifyItemChanged(position)
            }
        })
    }

    private fun wxPay(orderNo: String) {
        ApiService.orderPayWx(this, orderNo, object : DialogCallback<LzyResponse<PayWxInfo>>(){
            override fun onSuccess(response: Response<LzyResponse<PayWxInfo>>?) {
                val payWxInfo = response!!.body().data
                if (WXPayCommon.getInstance(activity).isWeixinAvilible) {
                    WXPayCommon.getInstance(activity).sendPayReq(payWxInfo)
                } else {
                    ToastUtils.showShort(activity, getString(R.string.wx_chat_install))
                }
            }
        })
    }

    override fun loadData(page: Int, pageCount: Int) {
        ApiService.deliveryList(this, type, page, object : DialogCallback<LzyResponse<Logistics>>(){
            override fun onSuccess(response: Response<LzyResponse<Logistics>>?) {
                onGetDataSuc(response!!.body().data.records)
            }
        })
    }

    override fun getData(): MutableList<Logistics> {
        return jieDanAdapter.data
    }

    override fun bindData(isRefresh: Boolean, list: MutableList<Logistics>?) {
        if (isRefresh){
            jieDanAdapter.setNewData(list)
        }else{
            jieDanAdapter.addData(list!!)
        }
    }

    override fun isBindEventBus(): Boolean {
        return true
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addrEven(item: WxPayEvent) {
        if (item.payCode == BaseResp.ErrCode.ERR_OK){
            ToastUtils.showShort(activity, "支付成功")
            if (mClickPos != -1){
                jieDanAdapter.getItem(mClickPos)?.paid = true
                jieDanAdapter.notifyItemChanged(mClickPos)
                mClickPos = -1
            }
            onRefresh(refreshLayout)
        }else if (item.payCode == BaseResp.ErrCode.ERR_USER_CANCEL){
            ToastUtils.showShort(activity, "支付取消")
        }else{
            ToastUtils.showShort(activity, "支付失败")
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addrEven(item: RefreshConfirmPeison) {
        if (type == 1){
            onRefresh(refreshLayout)
        }
    }
}